package org.example.rowing.controller;

import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.example.rowing.domain.RegistrationWithAthlete;
import org.example.rowing.enums.BoatTypeEnum;
import org.example.rowing.mapper.RoundScoreMapper;
import org.example.rowing.service.EventInfoService;
import org.example.rowing.service.RaceInfoService;
import org.example.rowing.service.RegistrationInfoService;
import org.example.rowing.service.TeamInfoService;
import org.example.rowing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class LaneExportController {
    @FXML
    public ComboBox<String> roundField;

    private Long raceId;

    @Autowired
    private RaceInfoService raceInfoService;

    // 用于在弹出框初始化时设置事件信息（用于编辑）
    public void initialize(Long raceId) {
        this.raceId = raceId;
        loadRounds(raceId);
    }

    private void loadRounds(Long raceId) {
        RoundScoreVO roundScoreVO = new RoundScoreVO();
        roundScoreVO.setRaceId(raceId);
        List<RoundScoreVO> roundScoreVOS = raceInfoService.showRoundScoreByCondition(roundScoreVO);
        log.info("xxx {}", roundScoreVOS);
        Set<String> rounds = new HashSet<>();
        for (RoundScoreVO scoreVO : roundScoreVOS) {
            rounds.add(scoreVO.getRound());
        }
        roundField.setItems(FXCollections.observableArrayList(rounds));
    }

    // 保存赛事
    @FXML
    private void handleExportEvent() {
        try {
            String round = roundField.getSelectionModel().getSelectedItem();

            // 1. 弹出文件保存对话框
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("保存抽签结果");
            fileChooser.setInitialFileName(round + "航道分配结果.xlsx");
            fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Excel 文件", "*.xlsx"));
            File file = fileChooser.showSaveDialog(roundField.getScene().getWindow());
            if (file == null) {
                return; // 用户取消或未选择文件
            }

            // 2. 创建 Workbook 和 Sheet
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("抽签结果");

            // 3. 从 laneAssignments 中解析航道编号，并建立 “航道编号 -> 队伍” 的映射
            //    laneAssignments: Map<teamName, laneString>  例如：{"西安队" -> "A组3号"}
            //    目标：构造一个按航道排序的结构，比如： A组3号 -> "西安队"
            //    如果一个航道上可能有多支队伍，则可改为 Map<Integer, List<String>>。
            RoundScoreVO roundScoreVO = new RoundScoreVO();
            roundScoreVO.setRaceId(raceId);
            roundScoreVO.setRound(round);
            List<RoundScoreVO> roundScoreVOS = raceInfoService.showRoundScoreByCondition(roundScoreVO);
            Map<String, RegistrationVO> laneToTeamMap = new TreeMap<>();  // 按航道编号升序排列
            String raceName = "";
            for (RoundScoreVO scoreVO : roundScoreVOS) {
                if (scoreVO.getStatus().equals("NORMAL")) {
                    RegistrationVO registrationVO = scoreVO.getRegistrationVO();
                    String lane = scoreVO.getLane();
                    raceName = registrationVO.getRace().getName();
                    laneToTeamMap.put(lane, registrationVO);
                }
            }

            // 设置字体样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short)12);
            headerStyle.setFont(headerFont);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);

            // 第一行：项目名称（合并单元格）
            Row row0 = sheet.createRow(0);
            org.apache.poi.ss.usermodel.Cell cell00 = row0.createCell(0);
            cell00.setCellValue(raceName);
            cell00.setCellStyle(headerStyle);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));

            // 第二行：导出日期
            String exportDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd"));
            Row row1 = sheet.createRow(1);
            org.apache.poi.ss.usermodel.Cell cell10 = row1.createCell(0);
            cell10.setCellValue("导出时间：" + exportDate);

            // 第三行：比赛轮次
            Row row2 = sheet.createRow(2);
            org.apache.poi.ss.usermodel.Cell cell20 = row2.createCell(0);
            cell20.setCellValue("当前轮次：" + round);

            // 5. 写入第一行：航道
            Row rowLane = sheet.createRow(3);
            // 第 0 列写“航道”
            rowLane.createCell(0).setCellValue("航道");

            // 6. 写入第二行：姓名
            Row rowName = sheet.createRow(4);
            rowName.createCell(0).setCellValue("姓名");

            // 7. 写入第三行：号码
            Row rowNumber = sheet.createRow(5);
            rowNumber.createCell(0).setCellValue("号码");

            // 8. 写入第四行：代表队
            Row rowTeam = sheet.createRow(6);
            rowTeam.createCell(0).setCellValue("代表队");

            Row rowRegistration = sheet.createRow(7);
            rowRegistration.createCell(0).setCellValue("报名编号");

            // 9. 按照 laneToTeamMap 的顺序依次将航道信息写入到列 1、2、3... 中
            int colIndex = 1; // 从第 1 列开始写
            for (Map.Entry<String, RegistrationVO> entry : laneToTeamMap.entrySet()) {
                String laneNumber = entry.getKey();
                RegistrationVO registrationVO = entry.getValue();

                // 航道
                rowLane.createCell(colIndex).setCellValue(laneNumber);

                // 姓名（用“、”连接）
                List<RegistrationWithAthlete> athletes = registrationVO.getAthletes();
                String joinedNames = athletes.stream()
                        .map(RegistrationWithAthlete::getAthleteName)
                        .collect(Collectors.joining("、"));
                rowName.createCell(colIndex).setCellValue(joinedNames);

                // 号码（用“、”连接）
                String joinedNumbers = athletes.stream()
                        .map(RegistrationWithAthlete::getAthleteNum)
                        .collect(Collectors.joining("、"));
                rowNumber.createCell(colIndex).setCellValue(joinedNumbers);

                // 代表队
                rowTeam.createCell(colIndex).setCellValue(registrationVO.getTeam().getName());

                rowRegistration.createCell(colIndex).setCellValue(registrationVO.getRegistrationId());

                colIndex++;
            }

            // 10. 自动调整列宽
            for (int i = 0; i <= laneToTeamMap.size(); i++) {
                sheet.autoSizeColumn(i);
                // 获取当前列宽
                int currentWidth = sheet.getColumnWidth(i);
                // 增加额外宽度，例如增加 40% 的宽度
                int extraWidth = (int)(currentWidth * 0.4);
                sheet.setColumnWidth(i, currentWidth + extraWidth);
            }

            try (FileOutputStream fos = new FileOutputStream(file)) {
                workbook.write(fos);
                showAlert("导出成功！");
            }

            workbook.close();
            closeWindow();
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            showAlert("导出失败：" + e.getMessage());
        }
    }

    private void showAlert(String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    // 取消操作，关闭弹出框
    @FXML
    private void handleCancel() {
        closeWindow();
    }

    private void closeWindow() {
        Stage stage = (Stage) roundField.getScene().getWindow();
        stage.close();
    }
}
